"""
@Project:${2108A}人工智能
@File:jwt_token.py
@Author:柴奇峰
@Date:21:32
"""

import jwt
from jwt import exceptions
from rest_framework.response import Response
from datetime import datetime,timedelta
from django.conf import settings


# 生成token
def generate_token(user):
    expiry = datetime.now() + timedelta(hours=3)
    payload = {
        'id':user.id,
        'account':user.account,
        'exp':expiry
    }
    try:
        token = jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')
        return token
    except Exception as e:
        print('生成token失败',e)
        return None


# 验证token
def verification_token(token):
    try:
        payload = jwt.decode(token,key=settings.SECRET_KEY,algorithms='HS256')
        return payload
    except exceptions.ExpiredSignatureError:
        return Response({'code':204,'msg':'token已过期'})
    except exceptions.DecodeError:
        return Response({'code':204,'msg':'非法token'})



